
import { Component, useState } from "react"

function DemoA() {
  let [todo, setTodo] = useState("");
  let [list, setList] = useState([]);
  let confirm = () => {
    if (!todo.trim()) {
      alert("输入框必须要输入内容");
      return;
    }
    setList([...list, { id: Date.now(), task: todo }])
    setTodo("")
  }
  let addByEnter = (e) => {
    if (e.keyCode == 13) {
      confirm();
    }
  }
  let delTodo = (id) => {
    setList(list.filter(item => item.id !== id))
  }
  return (
    <div>
      <div>
        <input
          type="text"
          value={todo}
          onChange={e => setTodo(e.target.value)}
          onKeyUp={e => addByEnter(e)}
        />
        <button onClick={confirm}>添加</button>
      </div>
      <div>
        {
          list.map((item, index, arr) => (
            <div key={item.id}>
              <span>{item.id}</span> -- <span>{item.task}</span>
              <button onClick={e => delTodo(item.id)}>删除</button>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default DemoA;